#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<sys/wait.h>

int main()
{
    int fd[2];
    if(pipe(fd) == -1)
    {
        perror("pipe failed");
        exit(1);
    }

    pid_t pid1 = fork();
    if(pid1 == 0)
    {
        close(fd[0]);
        char* args[] = {"ls", "-al" ,NULL};
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);
        execvp(args[0], args);
        perror("execvp failed");
        exit(1);
    }
    pid_t pid2 = fork();
    if(pid2 == 0)
    {
        int _fd = open("result.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
        if(_fd < 0)
        {
            perror("open failed");
            exit(1);
        }
        dup2(fd[0], STDIN_FILENO);
        dup2(_fd, STDOUT_FILENO);
        close(fd[0]);
        close(fd[1]);
        close(_fd);
        char* args[] = {"grep", "txt", NULL};
        execvp(args[0], args);
        perror("execvp grep");
        exit(1);
    }

    close(fd[0]);
    close(fd[1]);
    waitpid(pid1, NULL, 0);
    waitpid(pid2, NULL, 0);
    return 0;
}



